/**
 * 作文状态管理 Store
 * 管理作文列表、当前作文和CRUD操作
 */

import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import * as essayApi from '../services/essayApi.js';

export const useEssayStore = defineStore('essay', () => {
  // ==================== 状态 ====================

  /**
   * 作文列表
   */
  const essays = ref([]);

  /**
   * 当前正在编辑/查看的作文
   */
  const currentEssay = ref(null);

  /**
   * 加载状态
   */
  const loading = ref(false);

  /**
   * 错误信息
   */
  const error = ref(null);

  /**
   * 分页信息
   */
  const pagination = ref({
    total: 0,
    limit: 10,
    offset: 0,
    hasMore: false,
  });

  // ==================== 计算属性 ====================

  /**
   * 已完成批改的作文数量
   */
  const completedEssaysCount = computed(() => {
    return essays.value.filter((essay) => essay.status === 'completed').length;
  });

  /**
   * 待批改的作文数量
   */
  const pendingEssaysCount = computed(() => {
    return essays.value.filter(
      (essay) => essay.status === 'pending' || essay.status === 'processing'
    ).length;
  });

  /**
   * 是否有作文
   */
  const hasEssays = computed(() => essays.value.length > 0);

  /**
   * 当前作文是否已批改
   */
  const isCurrentEssayCorrected = computed(() => {
    return currentEssay.value?.status === 'completed';
  });

  // ==================== 操作 ====================

  /**
   * 获取作文列表
   * @param {Object} filters - 过滤条件
   * @param {number} filters.limit - 每页数量
   * @param {number} filters.offset - 偏移量
   * @param {string} filters.gradeLevel - 学段过滤
   * @param {string} filters.status - 状态过滤
   * @returns {Promise<Object>} 作文列表和分页信息
   */
  const fetchEssays = async (filters = {}) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[EssayStore] Fetch essays:', filters);

      // 调用真实API
      const response = await essayApi.list(filters);
      const { essays: essayList, pagination: paginationInfo } = response.data;

      // 更新state
      essays.value = essayList;
      pagination.value = paginationInfo;

      console.log('[EssayStore] Fetched', essayList.length, 'essays');
      return { success: true, data: { essays: essayList, pagination: paginationInfo } };
    } catch (err) {
      const errorMessage = err.message || '获取作文列表失败';
      error.value = errorMessage;
      console.error('[EssayStore] Fetch essays failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 根据ID获取作文详情
   * @param {string} essayId - 作文ID
   * @returns {Promise<Object>} 作文详情
   */
  const getEssayById = async (essayId) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[EssayStore] Get essay by ID:', essayId);

      // 调用真实API
      const response = await essayApi.getById(essayId);
      
      // 调试：打印响应结构
      console.log('[EssayStore] Get essay response:', response);
      
      // 后端返回格式：{ success, data, message }，其中data就是作文对象
      const essay = response.data;

      // 验证返回数据
      if (!essay || !essay.id) {
        console.error('[EssayStore] Invalid essay data:', { response, essay });
        throw new Error('服务器返回的作文数据格式不正确');
      }

      // 更新当前作文
      currentEssay.value = essay;

      // 更新到列表中（如果已存在则替换，否则添加）
      const existingIndex = essays.value.findIndex((e) => e.id === essayId);
      if (existingIndex >= 0) {
        essays.value[existingIndex] = essay;
      } else {
        essays.value.unshift(essay);
      }

      console.log('[EssayStore] Got essay:', essay.title);
      return { success: true, data: essay };
    } catch (err) {
      const errorMessage = err.message || '获取作文详情失败';
      error.value = errorMessage;
      console.error('[EssayStore] Get essay by ID failed:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 创建新作文
   * @param {Object} essayData - 作文数据
   * @param {string} essayData.title - 标题
   * @param {string} essayData.content - 内容
   * @param {string} essayData.gradeLevel - 学段
   * @param {Array} essayData.imageUrls - 图片URL数组（可选）
   * @returns {Promise<Object>} 创建的作文
   */
  const createEssay = async (essayData) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[EssayStore] Create essay:', essayData.title);

      // 调用真实API
      const response = await essayApi.create(essayData);
      
      // 调试：打印完整响应结构
      console.log('[EssayStore] Full response:', response);
      console.log('[EssayStore] response.data:', response.data);
      console.log('[EssayStore] response.data.data:', response.data?.data);
      
      // 后端返回格式：{ success, data, message }，其中data就是作文对象
      // API拦截器已经返回了response.data，所以这里需要再取一次.data
      const newEssay = response.data || response;

      // 验证返回数据
      if (!newEssay || !newEssay.id) {
        console.error('[EssayStore] Invalid response:', { response, newEssay });
        throw new Error('服务器返回的数据格式不正确');
      }

      // 添加到列表开头
      essays.value.unshift(newEssay);
      currentEssay.value = newEssay;

      console.log('[EssayStore] Essay created:', newEssay.id);
      return { success: true, data: newEssay };
    } catch (err) {
      // 使用友好的错误消息
      const errorMessage = err.message || '作文提交失败，请稍后重试';
      error.value = errorMessage;
      console.error('[EssayStore] Create essay failed:', err);
      
      // 返回格式化的错误
      throw {
        success: false,
        message: errorMessage,
        type: err.type || 'UNKNOWN_ERROR',
      };
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新作文
   * @param {string} essayId - 作文ID
   * @param {Object} updates - 要更新的字段
   * @returns {Promise<Object>} 更新后的作文
   */
  const updateEssay = async (essayId, updates) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[EssayStore] Update essay:', essayId, Object.keys(updates));

      // 调用真实API
      const response = await essayApi.update(essayId, updates);
      
      // 后端返回格式：{ success, data, message }，其中data就是作文对象
      const updatedEssay = response.data;

      // 验证返回数据
      if (!updatedEssay || !updatedEssay.id) {
        console.error('[EssayStore] Invalid updated essay data:', { response, updatedEssay });
        throw new Error('服务器返回的作文数据格式不正确');
      }

      // 更新列表中的作文
      const index = essays.value.findIndex((e) => e.id === essayId);
      if (index !== -1) {
        essays.value[index] = updatedEssay;
      }

      // 如果是当前作文，也更新当前作文
      if (currentEssay.value?.id === essayId) {
        currentEssay.value = updatedEssay;
      }

      console.log('[EssayStore] Essay updated:', essayId);
      return { success: true, data: updatedEssay };
    } catch (err) {
      const errorMessage = err.message || '更新作文失败';
      error.value = errorMessage;
      console.error('[EssayStore] Update essay failed:', err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 删除作文
   * @param {string} essayId - 作文ID
   * @returns {Promise<Object>} 删除结果
   */
  const deleteEssay = async (essayId) => {
    loading.value = true;
    error.value = null;

    try {
      console.log('[EssayStore] Delete essay:', essayId);

      // 调用真实API
      await essayApi.deleteEssay(essayId);

      // 从列表中移除
      const index = essays.value.findIndex((e) => e.id === essayId);
      if (index !== -1) {
        essays.value.splice(index, 1);
      }

      // 如果是当前作文，清空当前作文
      if (currentEssay.value?.id === essayId) {
        currentEssay.value = null;
      }

      console.log('[EssayStore] Essay deleted:', essayId);
      return { success: true };
    } catch (err) {
      const errorMessage = err.message || '删除作文失败';
      error.value = errorMessage;
      console.error('[EssayStore] Delete essay failed:', errorMessage);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 设置当前作文
   * @param {Object|null} essay - 作文对象或null
   */
  const setCurrentEssay = (essay) => {
    currentEssay.value = essay;
  };

  /**
   * 清空作文列表
   */
  const clearEssays = () => {
    essays.value = [];
    currentEssay.value = null;
    pagination.value = {
      total: 0,
      limit: 10,
      offset: 0,
      hasMore: false,
    };
  };

  // ==================== 返回 ====================

  return {
    // 状态
    essays,
    currentEssay,
    loading,
    error,
    pagination,

    // 计算属性
    completedEssaysCount,
    pendingEssaysCount,
    hasEssays,
    isCurrentEssayCorrected,

    // 操作
    fetchEssays,
    getEssayById,
    createEssay,
    updateEssay,
    deleteEssay,
    setCurrentEssay,
    clearEssays,
  };
});

